# -*- coding=utf-8 -*-
'''
Created on Aug 7, 2016

@author: corvo

'''

from sqlalchemy import desc
from Basehandler import BaseHandler
from Database.tables import Express
from Utlis.ReturnCodeConfig import CodeTable
from datetime import datetime, timedelta

delta = 24
class QueryHandler(BaseHandler):
    """
    查询信息, 十小时之内的资料将会被返回,
    可以自定制个数
    """
    
    def post(self):
        retjson = {'code':200, 'content': ''}

        _limit_start = 0        # 开始位置
        _limit_end   = 30       # 结束位置 + 1
        
        try:
            _limit_start = int(self.get_argument("start", 0))
            _limit_end   = int(self.get_argument("end", 5))

        except Exception as e:
            retjson['code'] = 300
            retjson['content'] = CodeTable[300]
            self.write_back(retjson)
            return
            
        
        # 获取`delta`小时以内的短信, 
        # 并且从`start`开始, 共返回`end` - `start`个数的记录
        # 例如start=0, end=5, 将会返回0-4共5条记录
        _info_list = self.db.query(Express)\
            .filter(Express.submittime > datetime.now() - timedelta(hours=delta))\
            .order_by(desc(Express.submittime)) \
            .offset(_limit_start)   \
            .limit(_limit_end - _limit_start)   
        #print (_info_list)
        try:
            _res = _info_list.all()
        except Exception as e:
            print (e)
            retjson['code'] = 500
            retjson['content'] = CodeTable[500]
            self.write_back(retjson);
            return


        retarray = []           # 返回数组
        for _info in _res:
#             print (_info)
            item = {'sms': _info.sms,
                    'user': _info.user,
                    'phone': _info.phone,
                    'dest': _info.dest,
                    'arrival': _info.arrival,
                    'locate': _info.locate,
                    'weight': _info.weight,
                    'sub_time': _info.submittime.strftime("%s"),
                    'receiving': _info.receiving,
                    'finish': _info.finish}
            retarray.append(item)

        retjson['content'] = retarray
        self.write_back(retjson)

    def get(self):
        pass

